package jp.co.menox.controller.tmserver.lend;

import java.util.Map;

import jp.co.menox.controller.tmserver.TmServerControllerBase;

import org.slim3.controller.Navigation;
import org.slim3.util.BeanUtil;
import org.slim3.util.CopyOptions;

import jp.co.menox.tmcommon.meta.LendingMeta;
import jp.co.menox.tmcommon.model.Lending;
import jp.co.menox.tmserver.service.LendingService;
import jp.co.menox.tmserver.service.CategoryService;

/**
 * 貸したい物を登録する画面
 * @author
 *
 */
public class RegisterLendController extends TmServerControllerBase {

    protected LendingService service;
    protected CategoryService categoryService;
    {
        service = new LendingService();
        categoryService = new CategoryService();
    }

    @Override
    public Navigation run() throws Exception {

        String command = this.asString("command");
        
        if (command != null && command.equals("register")) {
            Long userId = this.<Long>sessionScope("UserId");
            if (userId == null) {
                return forward("internal_error.jsp");
            }

            LendingMeta m = LendingMeta.get();
            Lending model = new Lending();
            // 入力値を設定
            BeanUtil.copy(request, model, 
                (new CopyOptions()).dateConverter("yyyy/MM/dd",  m.fromDate.getName(), m.toDate.getName()));
            // 新規登録
            model.setUserId(userId);
            model = service.insert(model);

            return forward("registerLendResult.jsp");
            
        }  else {
            // 表示用mapの取得
            Map<Long, String> categoryMap = categoryService.getCategoryMap();

            // 表示用変数設定
            requestScope("cateMap", categoryMap);
            
            return forward("registerLend.jsp");
        }
    }
}
